package dao

import (
	"context"
	"gorm.io/gorm"

	"password-verification-management-system/common"
	"password-verification-management-system/model"
)

type UserDao struct {
	*gorm.DB
}

func NewUserDao(ctx context.Context) *UserDao {
	return &UserDao{common.GetDB()}
}

func NewUserDaoByDB(db *gorm.DB) *UserDao {
	return &UserDao{db}
}

// CreateUser 创建用户
func (dao *UserDao) CreateUser(user *model.User) (err error) {
	err = dao.DB.Model(&model.User{}).Create(&user).Error
	return
}

// UpdateUserById 更新用户
func (dao *UserDao) UpdateUserById(id uint, user *model.User) (err error) {
	err = dao.DB.Model(&model.User{}).Where("id=?", id).Updates(&user).Error
	return
}

func (dao *AdminDao) GetUserEmailByName(username string) (admin *model.Admin, err error) {
	err = dao.DB.Model(&model.Admin{}).Where("username= ?", username).First(&admin).Error
	return
}

// ExistOrNotByAdminName 根据username判断是否存在该名字
func (dao *AdminDao) ExistOrNotByUserName(username string) (admin *model.User, exist bool, err error) {
	var count int64
	err = dao.DB.Model(&model.Admin{}).Where("username=?", username).
		Count(&count).Error
	if count == 0 {
		return nil, false, err
	}
	err = dao.DB.Model(&model.Admin{}).Where("username=?", username).
		First(&admin).Error
	if err != nil {
		return nil, false, err
	}
	return admin, true, nil
}
